package com.chenjiaru.util;

import com.chenjiaru.util.constant.Constant;
import com.chenjiaru.util.entity.ConnectInfo;
import org.apache.http.HttpHost;
import org.elasticsearch.client.RestClient;

import java.util.Arrays;

public class RestHighLevelClient {



    private static ConnectInfo connectInfo = new ConnectInfo();
    private static org.elasticsearch.client.RestHighLevelClient client = null;

    private RestHighLevelClient() {

    }


    /**
     * 单机连接（自适应集群）
     * @return
     */
    public static org.elasticsearch.client.RestHighLevelClient getInstance() {
        if (client == null) {
            synchronized (RestHighLevelClient.class) {
                if (client == null) {
                    connectInfo.setActive(YamlUtil.getValueToString(Constant.FILE_PATH, Constant.ELASTIC_SEARCH, Constant.ACTIVE));
                    connectInfo.setUris(YamlUtil.getValueToString(Constant.FILE_PATH, connectInfo.getActive(), Constant.URIS));
                    HttpHost[] httpHosts = Arrays.stream(connectInfo.getUris().split(",")).map(HttpHost::create).toArray(HttpHost[]::new);
                    client = new org.elasticsearch.client.RestHighLevelClient(RestClient.builder(httpHosts));
                }
            }
        }
        return client;
    }

}
